package com.zivwu.mvp.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatButton;

import com.zivwu.mvp.R;


public class ClockButton extends AppCompatButton {
    private int time = 60;
    String counted;


    private final int min = 1000;
    private Runnable runnable;

    public ClockButton(Context context) {
        super(context);
        init(context);
    }

    public ClockButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }


    public ClockButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context) {
        init(context, null);
    }

    private void init(Context context, AttributeSet attrs) {
        init(context, attrs, 0);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        counted = context.getString(R.string.quick_clock_button_counted);

        TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.ClockButton, defStyleAttr, 0);
        try {
            time = typedArray.getInt(R.styleable.ClockButton_end_time, time);
        } finally {
            typedArray.recycle();
        }
        setText(counted);

    }

    private void initRunnable() {
        runnable = new Runnable() {
            int i = time * min;

            @Override
            public void run() {
                if (i > min || i == min) {
                    String counting = getContext().getString(R.string.quick_clock_button_counting, i / min);
                    setText(counting);
                    i = i - min;
                    postDelayed(this, min);
                } else {
                    setText(counted);
                    setEnabled(true);
                }

            }
        };
    }


    public void setClockStart() {
        if (!isEnabled())
            return;
        initRunnable();
        setEnabled(false);
        post(runnable);
    }


    public void removeClockRunnable() {
        setEnabled(true);
        removeCallbacks(runnable);
    }


    @Override
    protected void onDetachedFromWindow() {
        removeClockRunnable();
        super.onDetachedFromWindow();
    }
}
